package com.example.chatweb.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.chatweb.entity.UserInfo;
import com.example.chatweb.mapper.UserMapper;
import com.example.chatweb.utils.MD5PassordUtil;
import jakarta.annotation.Resource;

public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public int addUser(String name, String email, String password) {
        try {
            UserInfo userInfo = new UserInfo();
            userInfo.setName(name);
            userInfo.setEmail(email);
            UserInfo userpwd = MD5PassordUtil.md5(password, userInfo);
            userInfo.setSalt(userpwd.getSalt());
            userInfo.setPassword(userpwd.getPassword());
            userMapper.insert(userInfo);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int deleteUser(String email) {
        try {
            UserInfo userInfo = userMapper.selectOne(new QueryWrapper<UserInfo>().eq("email", email));
            userMapper.deleteById(userInfo.getId());
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int updateUser(String name, String email, String password) {
        try {
            UserInfo userInfo = userMapper.selectOne(new QueryWrapper<UserInfo>().eq("email", email));
            userInfo.setName(name);
            userInfo.setEmail(email);
            UserInfo userpwd = MD5PassordUtil.md5(password, userInfo);
            userInfo.setSalt(userpwd.getSalt());
            userInfo.setPassword(userpwd.getPassword());
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public String selectUser(String email) {
        try {
            UserInfo userInfo = userMapper.selectOne(new QueryWrapper<UserInfo>().eq("email", email));
            return JSON.toJSONString(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
